package com.qiantu.phone.widget.viewmodel;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.entity.LoginBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.exception.ResultException;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.Md5Util;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.activity.EnterPhoneActivity;
import com.qiantu.phone.ui.activity.FamilyInfoActivity;
import com.qiantu.phone.ui.activity.InfoSupplementActivity;
import com.qiantu.phone.ui.activity.LoginActivity;
import com.qiantu.phone.utils.PhoneUUIDUtils;
import com.qiantu.phone.utils.StringUtil;
import com.qiantu.phone.widget.EditTextLayout;

public class PasswordLoginPresenter implements View.OnClickListener, TextWatcher {
    private LoginActivity parent;
    public View itemView;
    private EditTextLayout mEdtAccount;
    private View mEdtAccountLy;
    private TextView mTvErrorHint;
    private EditTextLayout mEdtPwd;
    private TextView mTvPwdErrorHint;
    private TextView mForgetPwd;
    private TextView mVerLogin;
    private TextView mBtnLogin;
    private PhoneStrAdapter phoneStrAdapter;
    private View dropdown;
    RecyclerView phoneRecyclerView;
    private boolean hasDropData;
    private View phoneListOutside;

    public PasswordLoginPresenter(LoginActivity parent, @IdRes int id) {
        itemView = parent.findViewById(R.id.pwd_login_ly);
        this.parent = parent;
        initView();
    }

    private void initView() {
        mEdtAccount = itemView.findViewById(R.id.edt_account1);
        mEdtAccountLy = itemView.findViewById(R.id.view2);
        mTvErrorHint = itemView.findViewById(R.id.tv_error_hint1);
        mEdtPwd = itemView.findViewById(R.id.edt_pwd);
        mTvPwdErrorHint = itemView.findViewById(R.id.tv_pwd_error_hint);
        mForgetPwd = itemView.findViewById(R.id.forget_pwd);
        mVerLogin = itemView.findViewById(R.id.ver_login);
        mBtnLogin = itemView.findViewById(R.id.btn_login);
        dropdown = itemView.findViewById(R.id.dropdown);
        mVerLogin.setOnClickListener(this::onClick);
        mForgetPwd.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        dropdown.setOnClickListener(this);
        phoneRecyclerView = parent.findViewById(R.id.phone_list);
        phoneListOutside = parent.findViewById(R.id.phone_list_outside);
        phoneListOutside.setOnClickListener(this::onClick);
        mEdtAccount.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11 ){
                    if (!StringUtil.isPhoneLegal(mEdtAccount.getText().toString())) {
                        mEdtAccountLy.setSelected(true);
                        mTvErrorHint.setText(R.string.phone_error_hint);
                        if (hasDropData) dropdown.setVisibility(View.GONE);
                        mEdtAccount.setIconVisible(false);
                    }else {
                        parent.hideKeyboard(mEdtAccount);
                    }
                }else {
                    mEdtAccountLy.setSelected(false);
                    mTvErrorHint.setText("");
                    if (hasDropData) dropdown.setVisibility(View.VISIBLE);
                    mEdtAccount.setIconVisible(true);
                }
            }
        });
        mEdtPwd.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mEdtPwd.setSelected(false);
                mTvPwdErrorHint.setText("");
                mEdtPwd.setIconVisible(true);
            }
        });
        mEdtPwd.getEditText().addTextChangedListener(this);
        mEdtAccount.getEditText().addTextChangedListener(this);

        hasDropData = !(AppApplication.getInstance().getAccounts() == null || AppApplication.getInstance().getAccounts().isEmpty());
        if (!hasDropData){
            dropdown.setVisibility(View.GONE);
            phoneRecyclerView.setVisibility(View.GONE);
        }else {
            phoneRecyclerView.setLayoutManager(new LinearLayoutManager(parent));
            phoneStrAdapter = new PhoneStrAdapter();
            phoneStrAdapter.setNewInstance(AppApplication.getInstance().getAccounts());
            phoneStrAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    mEdtAccount.setText(phoneStrAdapter.getData().get(position).getUserInfo().getPhone());
                    showPhoneLise(false);
                }
            });
            phoneRecyclerView.setAdapter(phoneStrAdapter);
            showPhoneLise(false);
        }
    }
    private void showPhoneLise(boolean b) {
        if (b){
            phoneListOutside.setVisibility(View.VISIBLE);
            dropdown.setSelected(true);
            phoneRecyclerView.setVisibility(View.VISIBLE);
        }else {
            dropdown.setSelected(false);
            phoneRecyclerView.setVisibility(View.GONE);
            phoneListOutside.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ver_login){
            parent.changeLoginType(true);
        }else if (id == R.id.btn_login){
            mEdtAccountLy.setSelected(false);
            loginwithpwd();
        }else if (id == R.id.forget_pwd){
            parent.startActivity(EnterPhoneActivity.class);
        }else if (id == R.id.dropdown){
            showPhoneLise(phoneRecyclerView.getVisibility()==View.GONE);
        }else if (id == R.id.phone_list_outside){
            showPhoneLise(false);
        }
    }

    private void loginwithpwd() {
        String androidId = PhoneUUIDUtils.getDeviceUUID(AppApplication.getInstance());
        String md5Pwd = Md5Util.getMD5ofStr(mEdtPwd.getText().toString());
        LLHttpManager.loginWithPwd(parent, mEdtAccount.getText().toString(), md5Pwd, androidId, AppApplication.getInstance().pushDeviceId, new HttpCallback<HttpData<LoginBean>>(parent){
            @Override
            public void onSucceed(HttpData<LoginBean> result) {
                super.onSucceed(result);
                AppApplication.getInstance().setCurLoginInfo(mEdtAccount.getText().toString(), result.getData());
                switch (result.getData().getRegistrationProgress()){
                    case 1:
                        InfoSupplementActivity.start(parent);
                        //关闭所有页面
                        ActivityManager.getInstance().finishAllActivities();
                        break;
                    case 2:
                        if(result.getData().isOwnHouse()){//已拥有房屋
                            AppApplication.getInstance().changeHouseData(parent, true, parent.getString(R.string.init_house_info));
                        }else{
                            FamilyInfoActivity.start(parent);
                            //关闭所有页面
                            ActivityManager.getInstance().finishAllActivities();
                        }
                        break;
                    case 3:
                        AppApplication.getInstance().changeHouseData(parent, true, parent.getString(R.string.init_house_info));
                        break;
                }
            }

            @Override
            public void onFail(Exception e) {
                if(e instanceof ResultException){
                    if (11018 == ((ResultException)e).getHttpData().getCode()){
                        mEdtPwd.setSelected(true);
                        mTvPwdErrorHint.setText(R.string.account_pwd_error);
                        mEdtPwd.setIconVisible(false);
                    }else{
                        ToastUtils.show(((ResultException)e).getHttpData().getMessage());
                    }
                }else {
                    super.onFail(e);
                }
            }
        });
    }

    public void setVisibility(boolean v) {
        itemView.setVisibility(v? View.VISIBLE : View.GONE);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        setBtnEnable();
    }

    public void setBtnEnable(){
        if (mEdtAccount.getText().length() == 11 && StringUtil.isPhoneLegal(mEdtAccount.getText().toString()) && !TextUtils.isEmpty(mEdtPwd.getText()) && parent.agreeCheckBox.isChecked()){
            mBtnLogin.setEnabled(true);
        }else {
            mBtnLogin.setEnabled(false);
        }
    }

    public String getAccountText() {
        return mEdtAccount.getText().toString();
    }

    public void setAccountText(String text) {
        mEdtAccount.setText(text);
    }

    private class PhoneStrAdapter extends BaseQuickAdapter<LoginBean, BaseViewHolder>{

        public PhoneStrAdapter() {
            super(R.layout.phone_str_ly);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, LoginBean item) {
            holder.setText(R.id.text, item.getUserInfo().getPhone());
        }
    }
}
